import json
import os
import sys
import shutil

import docker

src_path = "/home/xionghaonan/src-code"


def expand_code(GIT_REPO: str, GIT_COMMIT: str):
    parts = GIT_REPO.rsplit('/', 1)
    PACKAGE_NAME = parts[1] if len(parts) > 1 else GIT_REPO

    # 连接到Docker守护程序
    client = docker.from_env()

    # 获取所有容器列表
    containers = client.containers.list()

    # 打印所有容器的名称
    # for container in containers:
    #     print(container.name)

    # 选择要操作的容器名称
    container_name = "oe2403-osc-xiong"

    # 获取容器对象
    container = client.containers.get(container_name)

    # 在容器中执行命令
    command = f"""bash -c "cd /root && \
    rm -rf {PACKAGE_NAME} && \
    git clone {GIT_REPO} && \
    cd {PACKAGE_NAME} && \
    git checkout {GIT_COMMIT} && \
    rm -rf /root/home\:littlebear0729\:branches\:openEuler\:23.03/ && \
    cd /root && \
    osc co home\:littlebear0729\:branches\:openEuler\:23.03 empty && \
    cd /root/home\:littlebear0729\:branches\:openEuler\:23.03/empty && \
    cp -r /root/{PACKAGE_NAME}/* . && \
    rm -rf /var/tmp/build-root/23.03-riscv64/home/abuild/rpmbuild/BUILD/ && \
    osc build --trust-all-projects --no-verify 23.03 riscv64; \
    cp -r /root/home\:littlebear0729\:branches\:openEuler\:23.03/empty/.osc /var/tmp/build-root/23.03-riscv64/home/abuild/rpmbuild/BUILD/"
    """

    # output_directory : /var/tmp/build-root/23.03-riscv64/home/abuild/rpmbuild/BUILD/libemf-1.0.13
    print(command)

    result = container.exec_run(command, stream=True)

    for output in result.output:
        # 打印命令的输出
        print(output.strip().decode('utf-8'))

    # 关闭与Docker守护程序的连接
    client.close()


def copy_code(is_before: bool):
    build_path = "/home/xionghaonan/oe-volume/home/abuild/rpmbuild/BUILD"
    os.chdir(src_path)
    build_folder = os.listdir(build_path)
    print(build_folder)
    os.makedirs("before", exist_ok=True)
    os.makedirs("after", exist_ok=True)
    # OSC Config
    os.makedirs("osc-config/before", exist_ok=True)
    os.makedirs("osc-config/after", exist_ok=True)
    if is_before:
        shutil.copytree(build_path, src_path + "/before/" + build_folder[0], dirs_exist_ok=True)
        shutil.copytree(build_path + "/.osc", src_path + "/osc-config/before/" + build_folder[0], dirs_exist_ok=True)
    else:
        shutil.copytree(build_path, src_path + "/after/" + build_folder[0], dirs_exist_ok=True)
        shutil.copytree(build_path + "/.osc", src_path + "/osc-config/after/" + build_folder[0], dirs_exist_ok=True)


def code_diff():
    before_path = src_path + "/before/"
    after_path = src_path + "/after/"
    os.chdir(src_path)
    os.system(f"diff -ur -U5 {before_path} {after_path} > diff.patch")


def meta_output(pkg_name: str, repo_url: str, commit_before: str, commit_after: str):
    meta = {
        "pkg_name": pkg_name,
        "repo_url": repo_url,
        "commit_before": commit_before,
        "commit_after": commit_after
    }
    meta_json = json.dumps(meta)

    with open(os.path.join(src_path, "meta.json"), "w") as f:
        f.write(meta_json)
        f.close()
    return meta_json


if __name__ == '__main__':
    os.makedirs(src_path, exist_ok=True)

    # git_repo = sys.argv[1]
    # git_commit = sys.argv[2]
    # git_repo = "https://gitee.com/src-openeuler/libEMF"
    git_repo = "https://gitee.com/src-openeuler/libclc"
    git_commit = "a41c008d20ef52b72879dc13c3932793e6fdd81d"

    parts = git_repo.rsplit('/', 1)
    package_name = parts[1] if len(parts) > 1 else git_repo

    expand_code(git_repo, git_commit)
    copy_code(is_before=True)

    git_commit = "f6e9060a943f3bb75163ebea0dae7ef7f655fe7d"
    expand_code(git_repo, git_commit)
    copy_code(is_before=False)

    code_diff()

    os.rename(src_path, f"/home/xionghaonan/{package_name}")
    shutil.move(f"/home/xionghaonan/{package_name}", "/home/xionghaonan/diff_codes/")
